<template>

  <div style="width: 100%;">


    <div style="display: flex;background-color: white">
      <logo v-if="showLogo"  />
      <div class="right-menu">
        <template v-if="device!=='mobile'">
          <screenfull id="screenfull" class="right-menu-item hover-effect" />
        </template>
        <el-dropdown class="avatar-container right-menu-item hover-effect" trigger="click">
          <div class="avatar-wrapper">
            <img :src="avatar" class="user-avatar" @error="handleImageError">
            <i class="el-icon-caret-bottom" :style="{ color: settings.sideTheme === 'theme-dark' ? variables.menuBackground : variables.menuLightBackground }"/>
          </div>
          <el-dropdown-menu slot="dropdown">
            <router-link to="/user/profile">
              <el-dropdown-item>个人中心</el-dropdown-item>
            </router-link>
            <el-dropdown-item @click.native="setting = true">
              <span>布局设置</span>
            </el-dropdown-item>
            <el-dropdown-item divided @click.native="logout">
              <span>退出登录</span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>


    <el-menu
      :style="{ backgroundColor: settings.sideTheme === 'theme-dark' ? variables.menuBackground : variables.menuLightBackground }"
      :default-active="activeMenu"
      mode="horizontal"
      @select="handleSelect"
    >
      <template v-for="(item, index) in topMenus">
        <el-menu-item :style="{'--theme': theme}" :index="item.path" :key="index" v-if="index < visibleNumber"
        ><svg-icon :icon-class="item.meta.icon" />
          {{ item.meta.title }}</el-menu-item
        >
      </template>

      <!-- 顶部菜单超出数量折叠 -->
      <el-submenu index="more" v-if="topMenus.length > visibleNumber">
        <template slot="title"> 更多导航 </template>
        <template v-for="(item, index) in topMenus">
          <el-menu-item
            :index="item.path"
            :key="index"
            v-if="index >= visibleNumber"
          ><svg-icon :icon-class="item.meta.icon" />
            {{ item.meta.title }}</el-menu-item
          >
        </template>
      </el-submenu>
    </el-menu>

  </div>




</template>

<script>
import { constantRoutes } from "@/router";
import Logo from "@/layout/components/Sidebar/Logo";
import {mapGetters, mapState} from "vuex";
import variables from "@/assets/styles/variables.scss";
import Screenfull from '@/components/Screenfull'
export default {
  components: {
    Logo,
    Screenfull },
  data() {
    return {
      defaultAvatar:null,
      // 顶部栏初始数
      visibleNumber: 9,
      // 是否为首次加载
      isFrist: false,
      // 当前激活菜单的 index
      currentIndex: undefined
    };
  },
  computed: {
    setting: {
      get() {
        return this.$store.state.settings.showSettings
      },
      set(val) {
        this.$store.dispatch('settings/changeSetting', {
          key: 'showSettings',
          value: val
        })
      }
    },
    ...mapGetters([
      'avatar',
      'device'
    ]),
    ...mapState(["settings"]),
    variables() {
      return variables;
    },
    showLogo() {
      return this.$store.state.settings.sidebarLogo;
    },
    theme() {
      return this.$store.state.settings.theme;
    },
    // 顶部显示菜单
    topMenus() {
      let topMenus = [];
      this.routers.map((menu) => {
        if (menu.hidden !== true) {
          // 兼容顶部栏一级菜单内部跳转
          if (menu.path === "/") {
              topMenus.push(menu.children[0]);
          } else {
              topMenus.push(menu);
          }
        }
      });
      return topMenus;
    },
    // 所有的路由信息
    routers() {
      return this.$store.state.permission.topbarRouters;
    },
    // 设置子路由
    childrenMenus() {
      var childrenMenus = [];
      this.routers.map((router) => {
        for (var item in router.children) {
          if (router.children[item].parentPath === undefined) {
            if(router.path === "/") {
              router.children[item].path = "/redirect/" + router.children[item].path;
            } else {
			  if(!this.ishttp(router.children[item].path)) {
                router.children[item].path = router.path + "/" + router.children[item].path;
			  }
            }
            router.children[item].parentPath = router.path;
          }
          childrenMenus.push(router.children[item]);
        }
      });
      return constantRoutes.concat(childrenMenus);
    },
    // 默认激活的菜单
    activeMenu() {
      const path = this.$route.path;
      let activePath = this.routers[0].path;
      if (path.lastIndexOf("/") > 0) {
        const tmpPath = path.substring(1, path.length);
        activePath = "/" + tmpPath.substring(0, tmpPath.indexOf("/"));
      } else if ("/index" == path || "" == path) {
        if (!this.isFrist) {
          this.isFrist = true;
        } else {
          activePath = "index";
        }
      }
      let routes = this.activeRoutes(activePath);
      if (routes.length === 0) {
        activePath = this.currentIndex || this.routers[0].path
        this.activeRoutes(activePath);
      }
      return activePath;
    },
  },
  beforeMount() {
    window.addEventListener('resize', this.setVisibleNumber)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.setVisibleNumber)
  },
  mounted() {
    this.setVisibleNumber();
  },

  methods: {
    async logout() {
      this.$confirm('确定注销并退出系统吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('LogOut').then(() => {
          location.href = '/index';
        })
      }).catch(() => {});
    },
    handleImageError() {
      this.defaultAvatar= require("@/assets/images/profile.png")
    },
    // 根据宽度计算设置显示栏数
    setVisibleNumber() {
      const width = document.body.getBoundingClientRect().width /3;
      this.visibleNumber = parseInt(width / 50);
    },
    // 菜单选择事件
    handleSelect(key, keyPath) {
      this.currentIndex = key;
      if (this.ishttp(key)) {
        // http(s):// 路径新窗口打开
        console.log("http(s):// 路径新窗口打开")
        window.open(key, "_blank");
        this.$store.dispatch('settings/changeSetting', {
          key: 'showSidebar',
          value: false
        })
      } else if (key.indexOf("/redirect") !== -1) {
        // /redirect 路径内部打开
        console.log("redirect 路径内部打开")
        console.log(this.$router)
        this.$router.push({ path: key.replace("/redirect", "") });
        this.$store.dispatch('settings/changeSetting', {
          key: 'showSidebar',
          value: false
        })

      } else if (this.currentIndex === 'index') {
        //首页
        this.activeRoutes(key);
        this.$router.push({path: '/index'});
        this.$store.dispatch('settings/changeSetting', {
          key: 'showSidebar',
          value: false
        })
      }  else {
        // 显示左侧联动菜单
        console.log("显示左侧联动菜单:",key)
        this.activeRoutes(key);
        this.$store.dispatch('settings/changeSetting', {
          key: 'showSidebar',
          value: true
        })
        let selectMenu = this.topMenus.filter(item => item.path===key)
        if(selectMenu[0].children!==undefined && selectMenu[0].children.length>0){
          this.$router.push({ path: selectMenu[0].children[0].path });
        }

      }
    },
    // 当前激活的路由
    activeRoutes(key) {
      var routes = [];
      console.log("key:",key)
      if (this.childrenMenus && this.childrenMenus.length > 0) {
        this.childrenMenus.map((item) => {
          if (key == item.parentPath || (key == "index" && "" == item.path)) {
            routes.push(item);
          }
        });
      }
      if(routes.length > 0) {
        this.$store.commit("SET_SIDEBAR_ROUTERS", routes);
      }
      return routes;
    },
	ishttp(url) {
      return url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1
    }
  },
};
</script>

<style lang="scss" scoped>
.el-menu--horizontal > .el-menu-item {
  float: left;
  height: 40px;
  line-height: 40px;
  margin: 0;
  border-bottom: 5px solid #00dbba;
  text-align: center;
  font-size: 14px;
  color: white;
}


.el-menu--horizontal > .el-menu-item.is-active {
  border-bottom: 5px solid #00dbba;
  color: #0C71E0;
  background-color: transparent;
  color: white;
  font-weight: 700;
}


.el-menu--horizontal > .el-menu-item:not(.is-disabled):hover, .el-menu--horizontal > .el-menu-item:not(.is-disabled):focus {
  background-color: transparent;
  color: white;
}


.right-menu {
  display: flex;
  float: right;
  height: 48px;
  line-height: 48px;
  &:focus {
    outline: none;
  }
  .avatar-container {

    margin-right: 30px;
    .avatar-wrapper {
      position: relative;
      .user-avatar {
        margin-top: 10px;
        cursor: pointer;
        width: 30px;
        height: 30px;
        border-radius: 10px;
      }

      .el-icon-caret-bottom {
        cursor: pointer;
        position: absolute;
        right: -20px;
        top: 30px;
        font-size: 12px;
      }
    }
  }
}

.right-menu-item {
  display: inline-block;
  padding: 0 8px;
  height: 100%;
  font-size: 18px;
  color: white;
  vertical-align: text-bottom;

  &.hover-effect {
    cursor: pointer;
    transition: background .3s;

    &:hover {
      background: rgba(0, 0, 0, .025)
    }
  }
}

::v-deep .el-menu--horizontal > .el-submenu .el-submenu__title {
  height: 40px;
  line-height: 40px;
  color: white;
  border-bottom: 2px solid transparent;
  border-bottom-color: transparent;

  &:hover {
    background: rgba(0, 0, 0, .025)
  }

}

</style>
